package com.ds.esd.formula.service;

import com.ds.bpm.formula.ParticipantSelect;
import com.ds.common.JDSException;
import com.ds.common.util.StringUtility;
import com.ds.config.*;
import com.ds.enums.db.MethodChinaName;
import com.ds.esb.config.formula.FormulaParams;
import com.ds.esd.plugins.api.node.APIPaths;
import com.ds.esd.bpm.BPMFactory;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.custom.annotation.DialogAnnotation;
import com.ds.esd.custom.annotation.GridViewAnnotation;
import com.ds.esd.custom.annotation.PopTreeViewAnnotation;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.api.enums.CustomCallBack;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.custom.module.annotation.ModuleAnnotation;
import com.ds.esd.formula.component.ApiPopTree;
import com.ds.esd.formula.component.ApisPopTree;
import com.ds.esd.formula.component.grid.ApiGridView;
import com.ds.esd.project.config.FormulaInst;
import com.ds.esd.project.config.FormulaInstParams;
import com.ds.esd.project.config.ProjectConfig;
import com.ds.web.util.PageUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RequestMapping(path = "/admin/formula/component/api/")
@MethodChinaName(cname = "API参数", imageClass = "spafont spa-icon-c-webapi")

public class ApiFService {
    @GridViewAnnotation(addPath = "ApiPopTree")
    @RequestMapping("Index")
    @ModuleAnnotation(imageClass = "spafont spa-icon-c-webapi")
    @APIEventAnnotation(autoRun = true,bindMenu = CustomMenuItem.index)
    @ResponseBody
    public ListResultModel<List<ApiGridView>> getIndex(String projectName, String formulaInstId, String parameterCode) {
        ListResultModel<List<ApiGridView>> model = new ListResultModel<>();
        try {
            ProjectConfig config = ESDFacrory.getESDClient().getProjectByName(projectName).getConfig();
            FormulaInst inst = config.getFormulas().get(formulaInstId);
            List<FormulaInstParams> formulaParamList = new ArrayList<FormulaInstParams>();
            Collection<FormulaInstParams> formulaParams = inst.getParamsMap().values();
            for (FormulaInstParams param : formulaParams) {
                if (param.getParameterCode().equals(parameterCode)) {
                    param.getParameterValues().forEach((key, value) -> {
                        FormulaInstParams paramInst = new FormulaInstParams(param, key, value);
                        formulaParamList.add(paramInst);
                    });
                }
            }
            model = PageUtil.getDefaultPageList(formulaParamList, ApiGridView.class);
        } catch (JDSException e) {
            model = new ErrorListResultModel();
            ((ErrorListResultModel) model).setErrdes(e.getMessage());
        }

        return model;
    }

    @PopTreeViewAnnotation
    @ModuleAnnotation(dynLoad = true,  caption = "添加API")
    @RequestMapping("ApiPopTree")
    @DialogAnnotation(width = "300", height = "450")
    @APIEventAnnotation(bindMenu = CustomMenuItem.add)
    @ResponseBody
    public TreeListResultModel<List<ApiPopTree>> getApiPopTree(String formulaInstId, String parameterCode, String esdsearchpattern) {
        TreeListResultModel<List<ApiPopTree>> model = new TreeListResultModel<>();
        List<ApiPopTree> popTrees = new ArrayList<>();
        try {
            popTrees.add(new ApiPopTree(esdsearchpattern));
        } catch (JDSException e) {
            model = new ErrorListResultModel();
            ((ErrorListResultModel) model).setErrdes(e.getMessage());
        }
        model.setData(popTrees);
        return model;
    }


    @GridViewAnnotation(addPath = "ApisPopTree")
    @RequestMapping("Indexs")
    @ModuleAnnotation()
    @APIEventAnnotation(autoRun = true,bindMenu = CustomMenuItem.indexs)
    @ResponseBody
    public ListResultModel<List<ApiGridView>> getIndexs(String projectName, String formulaInstId, String parameterCode) {
        ListResultModel<List<ApiGridView>> model = new ListResultModel<>();
        return getIndex(projectName, formulaInstId, parameterCode);
    }

    @PopTreeViewAnnotation
    @RequestMapping("ApisPopTree")
    @DialogAnnotation(width = "300", height = "450")
    @ModuleAnnotation(dynLoad = true,  caption = "添加API")
    @APIEventAnnotation(bindMenu = CustomMenuItem.add)
    @ResponseBody
    public TreeListResultModel<List<ApisPopTree>> getApisPopTree(String formulaInstId, String parameterCode, String esdsearchpattern) {
        TreeListResultModel<List<ApisPopTree>> model = new TreeListResultModel<>();
        List<ApisPopTree> popTrees = new ArrayList<>();
        try {
            popTrees.add(new ApisPopTree(esdsearchpattern));
        } catch (JDSException e) {
            model = new ErrorListResultModel();
            ((ErrorListResultModel) model).setErrdes(e.getMessage());
        }
        model.setData(popTrees);
        return model;
    }


    @RequestMapping("addApi")
    @APIEventAnnotation(bindMenu = CustomMenuItem.treeSave, callback = {CustomCallBack.ReloadParent, CustomCallBack.Close})
    @ResponseBody
    public ResultModel<Boolean> addRole(String projectName, String ApiPopTree, String ApisPopTree, String formulaInstId, String parameterCode, FormulaParams paramsType) {
        ResultModel<Boolean> model = new ResultModel<>();
        try {
            ProjectConfig config = ESDFacrory.getESDClient().getProjectByName(projectName).getConfig();
            FormulaInst inst = config.getFormulas().get(formulaInstId);
            ParticipantSelect select = BPMFactory.getInstance(ESDFacrory.getESDClient().getSpace()).getFormulaById(inst.getParticipantSelectId());
            FormulaInstParams params = (FormulaInstParams) inst.getParamsMap().get(parameterCode);
            if (params == null) {
                params = new FormulaInstParams();
                params.setFormulaInstId(inst.getFormulaInstId());
                params.setParameterCode(parameterCode);
                params.setParameterName(parameterCode);
                if (paramsType != null && !paramsType.equals("")) {
                    params.setParamsType(paramsType);
                }
                inst.getParamsMap().put(parameterCode, params);
            }


            if (ApisPopTree != null && !ApisPopTree.equals("")) {
                String[] apiIds = StringUtility.split(ApisPopTree, ";");
                for (String apiId : apiIds) {
                    APIPaths apiPaths = ESDFacrory.getESDClient().getAPIPaths(apiId);
                    params.getParameterValues().put(apiPaths.getPath(), apiPaths.getName());
                }
            } else if (ApiPopTree != null) {
                params.getParameterValues().clear();
                APIPaths apiPaths = ESDFacrory.getESDClient().getAPIPaths(ApiPopTree);
                params.getParameterValues().put(apiPaths.getPath(), apiPaths.getName());
            }

            ESDFacrory.getESDClient().getProjectByName(projectName).updateConfig(config);
        } catch (JDSException e) {
            model = new ErrorResultModel();
            ((ErrorResultModel<Boolean>) model).setErrdes(e.getMessage());
        }


        return model;
    }


    @RequestMapping("delApi")
    @APIEventAnnotation(bindMenu = CustomMenuItem.delete, callback = {CustomCallBack.Reload})
    @ResponseBody
    public ResultModel<Boolean> delApi(String formulaInstId, String parameterCode, String projectName, String id) {
        ResultModel<Boolean> model = new ResultModel<>();
        try {
            ProjectConfig config = ESDFacrory.getESDClient().getProjectByName(projectName).getConfig();
            FormulaInst inst = config.getFormulas().get(formulaInstId);
            FormulaInstParams params = (FormulaInstParams) inst.getParamsMap().get(parameterCode);
            String[] apiIds = StringUtility.split(id, ";");

            for (String apiId : apiIds) {
                params.getParameterValues().remove(apiId);
            }
            ESDFacrory.getESDClient().getProjectByName(projectName).updateConfig(config);

        } catch (JDSException e) {
            model = new ErrorResultModel();
            ((ErrorResultModel<Boolean>) model).setErrdes(e.getMessage());
        }


        return model;
    }

    private FormulaInst getFormula(String projectId, String formulaInstId) throws JDSException {
        ProjectConfig config = ESDFacrory.getESDClient().getProjectById(projectId).getConfig();
        FormulaInst formulaInst = config.getFormulas().get(formulaInstId);
        return formulaInst;
    }


}
